import {FC} from "react";
import useGetComponentInfo from "../../../hooks/useGetComponentInfo";
import style from './Layers.module.scss'
import {Button, message} from "antd";
import {useDispatch} from "react-redux";
import {
  changeComponentIsHidden,
  changeSelectedId,
  moveComponent,
  toggleComponentLocked
} from "../../../redux/componentsReducer";
import classNames from "classnames";
import {EyeInvisibleOutlined, LockOutlined} from "@ant-design/icons";
import SortableContainer from "../../../components/DragSortable/SortableContainer";
import SortItems from "../../../components/DragSortable/SortItems";

const Layers: FC = () => {
  const {componentList, selectedId} = useGetComponentInfo()
  const dispatch = useDispatch()

  function handleClick(fe_id: string) {
    const curCom = componentList.find(it => it.fe_id === fe_id)
    if (curCom && curCom.isHidden) {
      message.info("不可选中已隐藏的")
    }
    if (selectedId !== fe_id) {
      dispatch(changeSelectedId(fe_id))
    }
  }

  function changeHidden(fe_id: string, isHidden: boolean) {
    dispatch(changeComponentIsHidden({fe_id, isHidden}))
  }

  function changeLocked(fe_id: string) {
    dispatch(toggleComponentLocked({fe_id}))
  }

  // SortableContainer items属性需要有id属性
  const componentListWithId = componentList.map(item => {
    return {
      ...item,
      id: item.fe_id
    }
  })

  function handleDragEnd(oldIndex: number, newIndex: number) {
    console.log('oldIndex', oldIndex, 'newIndex', newIndex)
    dispatch(moveComponent({oldIndex, newIndex}))
  }

  return <SortableContainer items={componentListWithId} onDragEnd={handleDragEnd}>
    {
      componentList.map(item => {
        const {fe_id, isLocked, isHidden = false, title} = item
        const selectedClassName = style.selected
        const titleDefaultCalssName = style.title
        const titleClassName = classNames({
          [selectedClassName]: selectedId === fe_id,
          [titleDefaultCalssName]: true
        })

        return (
          <SortItems key={fe_id} id={fe_id}>
            <div className={style.wrapper}>
              <div className={titleClassName} onClick={() => {
                handleClick(fe_id)
              }}>{title}</div>
              <div className={style.handler}>
                <Button
                  onClick={() => {
                    changeHidden(fe_id, !isHidden)
                  }}
                  className={isHidden ? 'btn' : ''}
                  icon={<EyeInvisibleOutlined/>}
                  type={isHidden ? 'primary' : 'text'}
                />
                <Button className={isLocked ? 'btn' : ''}
                        icon={<LockOutlined/>}
                        onClick={() => changeLocked(fe_id)}
                        type={isLocked ? 'primary' : 'text'}/>
              </div>
            </div>
          </SortItems>)
      })
    }
  </SortableContainer>
}
export default Layers
